import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:t3_constant/aui_colors.dart';
import 'package:t3_constant/aui_fonts.dart';
import 'package:t3_data_service/biz_data_source/map/address/city_pick/city_pick.dart';
import 'package:t3_foundation/t3_foundation.dart';
import 'package:t3_map/city_pick/src/page/city_picker_controller.dart';
import 'package:uikit/uikit.dart';

import '../widget/city_pick_tools.dart';
import '../widget/city_pick_view.dart';
import '../widget/index_bar.dart';

typedef CityPickerSelectedCallback = void Function(HostModel);

class CityPickerPage extends StatefulWidget {
  /// 搜索框站位字符串
  final String? hintText;
  /// 城市列表的类型
  final CityScope? cityScope;
  /// 自动关闭页面
  final bool? autoPop;
  /// 是否展示返回按钮
  final bool? showBack;
  /// 是否来自于Flutter
  final bool isFromFlutter;
  final String? uuid;

  const CityPickerPage({
    Key? key,
    this.hintText,
    this.cityScope,
    this.autoPop,
    this.showBack,
    this.isFromFlutter = false,
    this.uuid,
  }): super(key: key);

  @override
  _CityPickerPageState createState() => _CityPickerPageState();
}

class _CityPickerPageState extends State<CityPickerPage> {
  var controller = CityPickController();

  List<HostModel> cityList = [];
  List<HostModel> lastList = [];
  HostModel? _locationInfo;

  String _inputText = "";
  late FocusNode _focusNode;
  bool isFocusOn = false;
  late TextEditingController textEditingController;

  @override
  void initState() {
    super.initState();

    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    textEditingController = TextEditingController();

    /// 实时用户位置信息
    _locationInfo = controller.currentLocation();
    loadLocalData();
    loadRemoteData();

    _focusNode = FocusNode()
      ..addListener(() {
        setState(() {
          isFocusOn = _focusNode.hasFocus;
        });
      });
  }

  @override
  void dispose() {
    SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var contextPadding = MediaQuery.of(context).padding;
    return Scaffold(
      backgroundColor: AuiColors.aui_F7F8FC,
      body: Center(
        child: Column(
          children: [
            Container(
              color: Colors.white,
              height: contextPadding.top,
            ),
            buildSearchBar(contextPadding.top),
            const SizedBox(
              height: 8,
            ),
            ...currentContentViews(context),
          ],
        ),
      ),
    );
  }

  List<Widget> currentContentViews(BuildContext context) {
    CityPickContentType cityPickContentType = CityPickContentType.cityList;
    List<HostModel> searchList = currentSearchData();
    if (_inputText.isNotEmpty) {
      if (searchList.isNotEmpty) {
        cityPickContentType = CityPickContentType.searchList;
      } else {
        cityPickContentType = CityPickContentType.noSearchResult;
      }
    }
    switch (cityPickContentType) {
      case CityPickContentType.cityList:
        return [
          buildLocationView(),
          buildLastCities(),
          buildListView(),
        ];
      case CityPickContentType.searchList:
        return [buildSearchListView(searchList, context)];
      case CityPickContentType.noSearchResult:
        return [buildEmptyView()];
    }
  }

  /// 关闭页面
  void closePageCallback(HostModel? hostModel) {
    if (hostModel == null) {
      return;
    }
    controller.cacheLastCity(hostModel, widget.cityScope);

    var body = hostModel.toJson();
    body['scope'] = widget.cityScope?.cityType ?? 1;
    CityPickerData.cacheLastCity(hostModel, widget.cityScope);

    Map<String, Object> pa = {
      "city":hostModel.city as Object,
      "adCode":hostModel.adCode as Object,
    };
    BoostChannel.instance.sendEventToNative('cityDidChanged', pa);
    if (widget.isFromFlutter) {
      if (widget.autoPop == true) {
        BoostNavigator.instance.pop({
          'result' : 'data',
          'data' : body
        });
      } else {
         DataBus.global.post<CityPickResultEvent>(CityPickResultEvent(widget.uuid ?? '', hostModel));
      }
      return;
    }

    BoostChannel.instance
        .sendEventToNative('selectCity', Map<String, Object>.from(body));
    if (widget.autoPop == true) {
      BoostNavigator.instance.pop(body);
    }
  }

  /// 点击返回
  void didClickBack() {
    if (widget.isFromFlutter) {
      BoostNavigator.instance.pop({
        'result' : 'back'
      });
      return;
    }
    BoostChannel.instance.sendEventToNative('selectCity', {"action": "back"});
  }

  /// 点击取消
  void didClickCancel() {
    if (widget.isFromFlutter) {
      if (widget.showBack == true) {
        BoostChannel.instance.sendEventToNative("cancelAddressSelect", {
          "action" : 'cityPickBar'
        });
      } else {
        BoostNavigator.instance.pop({
          'result' : 'cancel'
        });
      }
      return;
    }
    if (widget.showBack == true) {
      BoostChannel.instance
          .sendEventToNative('selectCity', {"action": "cancel"});
    } else {
      BoostNavigator.instance.pop();
    }
  }
}

/// ----------------------------------------------------------------\\\
/// 城市列表展示
/// ----------------------------------------------------------------\\\
extension _CityPickerPageCityList on _CityPickerPageState {
  Expanded buildListView() {
    return Expanded(
      child: Container(
        color: AuiColors.aui_F7F8FC,
        padding: const EdgeInsets.only(left: 8.0, right: 8.0),
        child: CityPickView(
          data: cityList,
          itemCount: cityList.length,
          itemBuilder: (BuildContext context, int index) {
            HostModel model = cityList[index];
            return getListItem(context, model);
          },
          susItemHeight: 55,
          susItemBuilder: (BuildContext context, int index) {
            HostModel model = cityList[index];
            String tag = model.getIndexTag();
            return getSusItem(context, tag);
          },
          indexBarData: T3IndexUtils.getTagIndexList(cityList),
          indexBarOptions: const IndexBarOptions(
            color: Colors.transparent,
            downColor: Color(0xFFEEEEEE),
          ),
        ),
      ),
    );
  }

  Widget getSusItem(BuildContext context, String tag, {double susHeight = 36}) {
    return Container(
      height: susHeight,
      width: MediaQuery.of(context).size.width,
      padding: const EdgeInsets.only(left: 16.0),
      color: AuiColors.aui_F7F8FC,
      alignment: Alignment.centerLeft,
      child: Text(
        tag,
        softWrap: false,
        style: const TextStyle(
          fontSize: 14.0,
          color: AuiColors.aui_A5A7AD,
        ),
      ),
    );
  }

  Widget getListItem(BuildContext context, HostModel model) {
    return Container(
      color: Colors.white,
      child: ListTile(
        title: Text(
          model.city ?? "",
          style: const TextStyle(
              fontSize: 14.0,
              fontWeight: AuiFonts.regular,
              color: AuiColors.aui_1D2232),
        ),
        onTap: () async {
          closePageCallback(model);
        },
      ),
    );
  }
}

/// ----------------------------------------------------------------\\\
/// 展示搜索の结果
/// ----------------------------------------------------------------\\\
extension _CityPickerPageSearchData on _CityPickerPageState {
  Widget buildSearchListView(List<HostModel> searchList, BuildContext context) {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.only(left: 12, right: 12),
        child: MediaQuery.removePadding(
          context: context,
          removeTop: true,
          removeBottom: true,
          child: ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              HostModel hostModel = searchList[index];
              return searchItem(hostModel);
            },
            itemExtent: 55,
            itemCount: searchList.length,
          ),
        ),
      ),
    );
  }

  Widget searchItem(HostModel hostModel) {
    return InkWell(
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.only(left: 12, right: 12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(
              height: 20,
            ),
            Expanded(
              child: Text(
                hostModel.city ?? "",
              ),
            ),
            const Divider(
              height: 0.5,
            )
          ],
        ),
      ),
      onTap: () {
        closePageCallback(hostModel);
      },
    );
  }
}

/// ----------------------------------------------------------------\\\
/// 展示搜索无结果
/// ----------------------------------------------------------------\\\
extension _CityPickerPageNoSearchData on _CityPickerPageState {
  Widget buildEmptyView() {
    return Column(
      children: [
        const SizedBox(
          height: 72,
        ),
        Image(
          image: T3AssetImage.t3assets(T3AssetsName.icon_empty),
          width: 120,
          height: 120,
        ),
        const Text(
          '暂无结果，试试其他城市吧',
          style: TextStyle(
              color: AuiColors.aui_A5A7AD,
              fontSize: 14,
              fontWeight: AuiFonts.regular),
        )
      ],
    );
  }
}

/// ----------------------------------------------------------------\\\
/// 搜索bar展示
/// ----------------------------------------------------------------\\\
extension _CityPickerPageSearchBar on _CityPickerPageState {
  Container buildSearchBar(double statusBarHeight) {
    var showBack = widget.showBack ?? false;
    return Container(
      height: 9.0 * 2 + 40,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.0),
      ),
      padding: const EdgeInsets.only(top: 9, bottom: 9, left: 12, right: 12),
      child: Container(
        color: Colors.white,
        child: Row(
          children: [
            Visibility(
              child: SizedBox(
                width: 32,
                height: 32,
                child: IconButton(
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                  icon: const Icon(
                    Icons.arrow_back_ios,
                    color: Color(0xFF535353),
                    size: 16,
                  ),
                  onPressed: () {
                    didClickBack();
                  },
                ),
              ),
              visible: showBack,
            ),
            Expanded(
              child: Container(
                // height: 40,
                decoration: const BoxDecoration(
                  color: AuiColors.aui_F7F8FC,
                  borderRadius: BorderRadius.all(Radius.circular(8)),
                ),
                padding: EdgeInsets.only(left: (showBack ? 1 : 8)),
                child: Padding(
                  padding: const EdgeInsets.only(left: 2.0),
                  child: buildSearchTextField(),
                ),
              ),
            ),
            const SizedBox(
              width: 7,
            ),
            InkWell(
              onTap: () {
                didClickCancel();
              },
              child: const SizedBox(
                width: 43,
                height: 60,
                child: Center(
                  child: Text(
                    '取消',
                    style: TextStyle(
                        color: AuiColors.aui_777A84,
                        fontSize: 14,
                        fontWeight: AuiFonts.regular),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildSearchTextField() {
    return TextField(
      controller: textEditingController,
      focusNode: _focusNode,
      decoration: InputDecoration(
        counterText: '',
        isDense: true,
        focusedBorder: InputBorder.none,
        disabledBorder: InputBorder.none,
        errorBorder: InputBorder.none,
        focusedErrorBorder: InputBorder.none,
        enabledBorder: InputBorder.none,
        border: InputBorder.none,
        contentPadding: const EdgeInsets.symmetric(vertical: 10),
        hintText: widget.hintText,
        hintStyle: const TextStyle(
            fontWeight: AuiFonts.regular,
            fontSize: 14,
            color: AuiColors.aui_A5A7AD),
        suffixIconConstraints: const BoxConstraints(minWidth: 20),
        suffixIcon: isFocusOn
            ? SizedBox(
          child: IconButton(
            alignment: Alignment.center,
            iconSize: 16,
            icon: T3Image.t3assets(
              T3AssetsName.icon_contact_phone_clear,
              width: 16,
              height: 16,
            ),
            onPressed: () {
              setState(() {
                _inputText = '';
                textEditingController.clear();
              });
            },
          ),
        )
            : const Text(""),
      ),
      maxLines: 1,
      cursorColor: const Color(0xFFFF8533),
      showCursor: true,
      cursorWidth: 2,
      onChanged: (content) {
        setState(() {
          _inputText = content;
        });
      },
    );
  }
}

/// ----------------------------------------------------------------\\\
/// 展示历史数据
/// ----------------------------------------------------------------\\\
extension _CityPickerPageHistory on _CityPickerPageState {
  Visibility buildLastCities() {
    return Visibility(
      visible: lastList.isNotEmpty,
      child: Container(
        height: 92,
        color: AuiColors.aui_F7F8FC,
        padding: const EdgeInsets.only(left: 8, right: 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: const EdgeInsets.only(top: 8),
              color: Colors.white,
              child: const SizedBox(
                height: 30,
                width: double.infinity,
                child: Padding(
                  padding: EdgeInsets.only(left: 12),
                  child: Text(
                    '最近访问',
                    style: TextStyle(
                        color: AuiColors.aui_A5A7AD,
                        fontSize: 14,
                        fontWeight: AuiFonts.regular),
                  ),
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.only(top: 7),
              height: 48,
              width: MediaQuery.of(context).size.width,
              color: Colors.white,
              child: _buildLastButtons(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLastButtons() {
    var count = lastList.length;
    var leading = 12.0;
    var gap = 10.0;
    var maxCityWidth = 106.0;

    final double width = MediaQuery.of(context).size.width - 16;
    var buttonWidth = (width - 2 * leading - gap * 2) / 3.0;
    if (buttonWidth > maxCityWidth) {
      buttonWidth = maxCityWidth;
      gap = (width - 2 * leading - buttonWidth * 3) / 2.0;
    }
    return Padding(
      padding: const EdgeInsets.only(left: 12, right: 12),
      child: Wrap(
        spacing: gap,
        alignment: WrapAlignment.start,
        children: [...buildLastButtons(buttonWidth)],
      ),
    );
  }

  List<Widget> buildLastButtons(double buttonWidth) {
    List<Widget> result = [];
    for (var item in lastList) {
      var button = InkWell(
        onTap: () {
          closePageCallback(item);
        },
        child: Container(
          width: buttonWidth,
          height: 32,
          alignment: Alignment.center,
          child: Padding(
            padding: const EdgeInsets.only(left: 4.0),
            child: Text(
              item.city ?? "",
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
              style: const TextStyle(
                color: AuiColors.aui_1D2232,
                fontWeight: AuiFonts.regular,
                fontSize: 14,
              ),
            ),
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            border: Border.all(width: 1, color: const Color(0xFFF2F2F2)),
          ),
        ),
      );
      result.add(button);
    }
    return result;
  }
}

/// ----------------------------------------------------------------\\\
/// 展示定位数据
/// ----------------------------------------------------------------\\\
extension _CityPickerPageLocation on _CityPickerPageState {
  Visibility buildLocationView() {
    return Visibility(
      visible: (_locationInfo != null),
      child: InkWell(
        child: Container(
          height: 60,
          color: AuiColors.aui_F7F8FC,
          padding: const EdgeInsets.only(top: 0, left: 8, right: 8),
          child: Container(
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(12),
                    topRight: Radius.circular(12))),
            child: Row(
              children: [
                const SizedBox(
                  width: 12,
                ),
                const SizedBox(
                  width: 60,
                  child: Text(
                    '当前定位',
                    style: TextStyle(
                        color: AuiColors.aui_A5A7AD,
                        fontSize: 14,
                        fontWeight: AuiFonts.regular),
                  ),
                ),
                const SizedBox(
                  width: 2,
                ),
                T3Image.t3assets(T3AssetsName.icon_yellow_location,
                    width: 16, height: 16),
                const SizedBox(
                  width: 8,
                ),
                SizedBox(
                  height: 30,
                  child: Center(
                    child: Text(
                      (_locationInfo != null)
                          ? (_locationInfo!.city ?? "")
                          : '',
                      style: const TextStyle(
                          fontWeight: AuiFonts.medium,
                          fontSize: 20,
                          color: AuiColors.aui_1D2232),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        onTap: () {
          var host = getModelFromName(_locationInfo?.city ?? "");
          if (host == null) {
            return;
          }
          closePageCallback(host);
        },
      ),
    );
  }
}

/// ----------------------------------------------------------------\\\
/// 展示数据处理：请求、本地数据、数据过滤
/// ----------------------------------------------------------------\\\
extension _CityPickerPageData on _CityPickerPageState {
  List<HostModel> currentSearchData() {
    List<HostModel> searchList = [];
    if (_inputText.isNotEmpty) {
      bool isChinese = ChineseHelper.isChinese(_inputText);
      for (var host in cityList) {
        if (isChinese) {
          if (host.city?.contains(_inputText) ?? false) {
            searchList.add(host);
          }
        } else {
          if (host.pinyinSearching.contains(_inputText)) {
            searchList.add(host);
          }
        }
      }
    }
    return searchList;
  }

  HostModel? getModelFromName(String name) {
    for (var host in cityList) {
      if (host.city == name) {
        return host;
      }
    }
    return null;
  }

  void loadLocalData() async {
    List<HostModel> list = await controller.getLastCities(widget.cityScope);
    if (mounted) {
      setState(() {
        lastList = list;
      });
    }
  }

  void loadRemoteData() {
    if (widget.cityScope == CityScope.all) {
      var list = controller.getAllCity((p0) {
        /// 全国数据为空，使用开城数据补充
        if (p0.isEmpty) {
          loadRemoteCities();
        } else {
          handleRemoteList(p0);
        }
      });
    } else {
      loadRemoteCities();
    }
  }

  void loadRemoteCities() async {
    controller.getOpenCity(widget.cityScope, (p0) {
      handleRemoteList(p0);
    });
  }

  void handleRemoteList(List<OpenCity> list) {
    if (list.isEmpty) {
      return;
    }
    List<HostModel> items = [];
    for (var openCity in list) {
      var city = openCity.cityName ?? '';
      var cityID = openCity.amapCityCode;
      var amapCityCode = openCity.amapCityCode;
      String pinyin = PinyinHelper.getPinyinE(city, separator: '');
      var adCode = openCity.cityCode ?? "320115";
      double latitude = 0;
      double longitude = 0;
      if (openCity.center != null) {
        List<String> center = openCity.center!.split(',');
        if (center.length == 2) {
          longitude = double.parse(center.first);
          latitude = double.parse(center.last);
        }
      }
      var hostModel = HostModel(
          city: city,
          cityID: cityID,
          amapCityCode: amapCityCode,
          adCode: adCode,
          latitude: latitude,
          longitude: longitude);
      String tag = pinyin.substring(0, 1).toUpperCase();
      if (RegExp('[A-Z]').hasMatch(tag)) {
        hostModel.tag = tag;
      }
      hostModel.pinyinSearching = pinyin;
      items.add(hostModel);
    }
    if (items.isEmpty) {
      return;
    }
    T3IndexUtils.sortListByTag(items);
    T3IndexUtils.setShowStatus(items);
    if (mounted) {
      setState(() {
        cityList = items;
      });
    }
  }
}
